<template>
  <div class="wrapp">
    <div class="head">
      <div class="title">合同模板</div>
      <Button @click="back">返回上一級</Button>
    </div>
    <div class="banner">
      <div class="item">
        <span>矿机单价：</span>
        <Input style="width: 200px" v-model="inputContent.a" />
      </div>
      <div class="item">
        <span>台数：</span>
        <Input style="width: 200px" v-model="inputContent.b" />
      </div>
      <div class="item">
        <span>矿场主单台成本：</span>
        <Input style="width: 200px" v-model="inputContent.c" />
      </div>
      <div class="item">
        <span>合同编号：</span>
        <Input style="width: 200px" v-model="inputContent.contractNo" />
      </div>
      <div class="item">
        <span class="ml">过期时间：</span>
        <Row style="display:inline-block;margin-right:10px;">
          <Col>
          <DatePicker type="date" placeholder="Select date" style="width: 200px" :value="time.startDate" @on-change="action"></DatePicker>
          </Col>
        </Row>
        <p>~</p>
        <Row style="display:inline-block;margin-left:10px;">
          <Col>
          <DatePicker type="date" placeholder="Select date" style="width: 200px" :value="time.endDate" @on-change="cut"></DatePicker>
          </Col>
        </Row>
      </div>
      <div class="select">
        <div class="box">
          <div class="boxContent" id="boxContent">
            <div class="boxContentSon">
              <CheckboxGroup v-model="fruit" class="checkboxGroup" @on-change="selectFun" id="checkboxGroup">
                <div class="contentItem" v-for="(item,index) in selectData" :key="index">
                  <Checkbox :label="item.userId+'/'+item.userName+'/'+item.projectRoleId+'?'+item.projectRole">{{item.userName}}/{{item.projectRole}}</Checkbox>
                </div>
              </CheckboxGroup>
            </div>
          </div>
        </div>
      </div>
      <div class="itemGuiZe">
        <!-- <h1>总分润规则：</h1>
        <div v-for='(item,index) in arrFirst' :key="index">
          <span>当收益累计在{{item.intervalBegin}}~{{item.intervalEnd}}元时，客户方分润：{{item.percent}}%</span>
        </div> -->
        <div class="type">
          <Button type="primary" @click="addToItem('客户方')">添加客户方</Button>
          <Button type="primary" @click="addToItem('平台方')">添加平台方</Button>
        </div>
        <h1>客户方分润：</h1>
        <div class="bannerItem" style="width:550px">
          <div class="boxContent">
            <div class="boxContentSon_1">
              <div class="srcroll">
                <div class="contentItem" v-for="(item,index) in clientArry" :key="index">
                  <span>{{item.userName}}</span>
                  <span>{{item.projectRole}}</span>

                  <Button type="primary" size="small" style="width:55px;height:27px" @click="remove(index)">移除</Button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <h1>平台方分润：</h1>
        <div class="bannerItem" style="width:600px">
          <div class="boxContent">
            <div class="boxContentSon_1">
              <div class="srcroll">
                <div class="contentItem" v-for="(item,index) in platformArry" :key="index">
                  <div style="width:200px">
                    <span>姓名：{{item.userName}}</span>
                    <span style="margin-left:30px">角色：{{item.projectRole}}</span>
                  </div>
                  <div>
                    <span>分润：</span>
                    <Input v-model="item.percent" style="width:100px" />
                  </div>

                  <Button type="primary" size="small" style="width:55px;height:27px" @click="removePT(index)">移除</Button>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
      <Button @click="queding">确定</Button>
    </div>
    <!-- 选择客户参与者 -->
    <Modal v-model="participantShow" :mask-closable="false" width="1076" cancel-text>
      <!-- <Input search enter-button placeholder="手机号/用户名/钱包地址" style="width:300px;margin-bottom:20px;" @on-search="searchParticipant" v-model="searchParticipantData" /> -->
      <Table :columns="participantColumns" :data="participantShowData" :border="true" :loading="isParticipantLoading"></Table>
      <Page :total="participantTotal" :current="participantPageNum" :page-size="participantPageSize" show-total placement="top" @on-change="participantHandlePage" style="margin-top:20px;"></Page>
    </Modal>

    <Modal v-model="check" :mask-closable="false" width="1076" cancel-text @on-ok="ok">
      <div>合同编号：{{checkData.contractNo}}</div>
      <div>算例{{checkData.powerAmount}}</div>
      <div>过期时间{{checkData.startDate}}~{{checkData.endDate}}</div>
      <div>
        <span> 客户方：</span>
        <div>
          <div v-for="(item,index) in clientArry" :key="index">
            <span>区间：{{item.intervalBegin}}~{{item.intervalEnd}}</span>
            <span style="margin-left:20px">人：</span>
            <span>{{item.userName}}</span>
            <span style="margin-left:20px">角色：</span>
            <span>{{item.projectRole}}</span>
            <span style="margin-left:20px">分润比例：</span>
            <span>{{item.percent}}</span>
          </div>
        </div>
      </div>
      <div>
        <span>平台方：</span>
        <div>
          <div v-for="(item,index) in platformArry" :key="index">
            <span>区间：{{item.intervalBegin}}~{{item.intervalEnd}}</span>
            <span style="margin-left:20px">人：</span>
            <span>{{item.userName}}</span>
            <span style="margin-left:20px">角色：</span>
            <span>{{item.projectRole}}</span>
            <span style="margin-left:20px">分润比例：</span>
            <span>{{item.percent}}</span>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 选择平台方参与者
    <Modal v-model="pTShow" :mask-closable="false" width="1076" cancel-text>
      <Input search enter-button placeholder="手机号/用户名/钱包地址" style="width:300px;margin-bottom:20px;" @on-search="searchPt" v-model="searchPtData" />
      <Table :columns="pTColumns" :data="pTShowData" :border="true" :loading="isParticipantLoading"></Table>
      <Page :total="pTTotal" :current="pTPageNum" :page-size="PtPageSize" show-total placement="top" @on-change="pTHandlePage" style="margin-top:20px;"></Page>
    </Modal> -->
  </div>
</template>

<script>
import apis from "../../util/apis.js"
export default {
  name: "Modle",
  data() {
    return {
      selectData: [],
      clientArry: [],
      platformArry: [],
      fruit: [],
      containerData: [],
      getParams: null,
      checkData: {
        contractNo: null,
        powerAmount: null,
        startDate: null,
        endDate: null,
        clientArry: null,
        platformArry: null,
        projectId: null
      },
      check: false,
      time: {
        startDate: null,
        endDate: null
      },
      contractNo: null,
      currentid_PT: null,
      currentid_1: null,
      containData: [
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        }
      ],
      pTArray: [
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
        {
          phone: "",
          percent: "",
          remark: "",
          userId: "",
          projectRole: "",
          projectRoles: []
        },
      ],
      inputContent: {
        a: null,
        b: null,
        c: null,
        contractNo: null
      },
      preview: [],
      arrFirst: [
      ],
      arrKeHu: [
      ],
      arrPt: [
      ],
      controlKeHu: null,
      participantShow: false,
      participantShowData: [],
      isParticipantLoading: false,
      participantTotal: 0,
      participantPageNum: 1,
      participantPageSize: 10,
      pTShow: false,
      participantColumns: [
        {
          title: "姓名",
          key: "userName",
          align: "center"
        },
        {
          title: "手机号码",
          key: "mobile",
          align: "center"
        },
        {
          title: "钱包地址",
          key: "wallet",
          align: "center"
        },
        {
          title: "选择",
          key: "chose",
          width: 70,
          align: "center",
          render: (h, params) => {
            let id = params.row.userId;
            let flag = false;
            if (this.currentid_1 === id) {
              flag = true;
            } else {
              flag = false;
            }
            let self = this;
            return h("div", [
              h("Radio", {
                props: {
                  value: flag
                },
                on: {
                  "on-change": () => {
                    self.currentid_1 = id;
                    let chuLi = null;
                    let chuLiArry = null;
                    if (params.row.roles.length > 0) {
                      chuLiArry = params.row.roles;
                      let characterList = this.comFun(chuLiArry);
                      this.containData[this.controlKeHu].projectRoles = characterList;
                      if (characterList.length === 1) {
                        this.containData[this.controlKeHu].projectRole = characterList[0].value;
                      }
                    } else {
                      this.containData[this.controlKeHu].projectRoles = null;
                    }
                    this.containData[this.controlKeHu].phone = params.row.userName + "/" + params.row.mobile;
                    this.containData[this.controlKeHu].userId = params.row.userId;
                    console.log(this.containData)
                  }
                }
              })
            ]);
          }
        }
      ],
      ///////平台方////////
      pTColumns: [
        {
          title: "姓名",
          key: "userName",
          align: "center"
        },
        {
          title: "手机号码",
          key: "mobile",
          align: "center"
        },
        {
          title: "钱包地址",
          key: "wallet",
          align: "center"
        },
        {
          title: "选择",
          key: "chose",
          width: 70,
          align: "center",
          render: (h, params) => {
            let id = params.row.userId;
            let flag = false;
            if (this.currentid_PT === id) {
              flag = true;
            } else {
              flag = false;
            }
            let self = this;
            return h("div", [
              h("Radio", {
                props: {
                  value: flag
                },
                on: {
                  "on-change": () => {
                    self.currentid_PT = id;
                    let chuLi = null;
                    let chuLiArry = null;
                    console.log(this.controlPT)
                    if (params.row.roles.length > 0) {
                      chuLiArry = params.row.roles
                      let characterList = this.comFun(chuLiArry);
                      this.pTArray[this.controlPT].projectRoles = characterList;
                      if (characterList.length === 1) {
                        this.pTArray[this.controlPT].projectRole = characterList[0].value;
                      }

                    } else {
                      this.pTArray[this.controlPT].projectRoles = null;
                    }
                    this.pTArray[this.controlPT].phone = params.row.userName + "/" + params.row.mobile;
                    this.pTArray[this.controlPT].userId = params.row.userId;

                  }
                }
              })
            ]);
          }
        }
      ],
      pTShowData: [],
      pTTotal: 0,
      pTPageNum: 1,
      PtPageSize: 10,
      controlPT: null,
      //////////项目用户列表//////
      projectUserData: null,
      //////平台方的人/////
      PTFarry: []
    };
  },
  mounted() {
    this.getParams = this.$route.query.param;
    this.projectUser();
  },
  methods: {
    back() {
      this.$router.push({
        name: "ProjectDetail",
        query: {
          param: this.getParams,
          proName: "rule"
        }
      });
    },
    action(date) {
      this.time.startDate = date;
    },
    cut(date) {
      this.time.endDate = date;
    },
    set() {
      let a = parseInt(this.inputContent.a);
      let b = parseInt(this.inputContent.b);
      let c = parseInt(this.inputContent.c);
      this.computeFirs(a, b, c);
      this.computeKehu(a, b, c);
    },
    queding() {
      let a = parseInt(this.inputContent.a);
      let b = parseInt(this.inputContent.b);
      let c = parseInt(this.inputContent.c);
      let resultKeHu = c * b + a * b;
      let resultGong = a * b;
      let resultZhu = b * c;
      let percentGong = (resultGong / (resultGong + resultZhu)).toFixed(2);
      let percentZhu_1 = parseFloat(percentGong)
      let percentZhu = (1 - percentZhu_1).toFixed(2);
      this.clientArry.forEach(element => {
        element.allotType = 2;
        element.intervalBegin = 0;
        element.intervalEnd = resultKeHu;
        if (element.projectRoleId === "01") {
          element.percent = parseFloat(percentGong) * 100;
        } else {
          element.percent = parseFloat(percentZhu) * 100;
        }
      })
      console.log(this.clientArry)
      let clientArry_1 = this.clientArry.slice();
      clientArry_1.forEach(element => {
        if (element.projectRoleId === '01') {
          element.intervalBegin = 0;
          element.intervalEnd = resultKeHu;
          element.percent = 0;
        } else {
          element.intervalBegin = resultKeHu;
          element.intervalEnd = null;
          element.percent = 100;
        }
      })
      console.log(clientArry_1)
      this.clientArry = this.clientArry.concat(clientArry_1);
      // console.log(this.clientArry)
      this.platformArry.forEach(element => {
        element.allotType = 3;
      })
      this.arrFirst = this.computeFirs(a, b, c);
      this.arrFirst.forEach(element => {
        element.allotType = 1;
      })
      let param = {};
      param.contractNo = this.inputContent.contractNo;
      param.details = this.clientArry.concat(this.platformArry, this.arrFirst);
      param.endDate = this.time.endDate + "23:59:59";
      param.startDate = this.time.startDate + "00:00:00";
      param.powerAmount = 72 * b;
      param.projectId = this.getParams.row.id;
      this.checkData = param;
      this.check = true;
    },
    ///////////选择客户/////////
    participantHandlePage(value) {
      this.participantPageNum = value;
      this.getparticipantData(this.participantPageNum - 1);
    },
    select(index) {
      this.controlKeHu = index;
      this.participantShow = true;
      this.getparticipantData(0);
    },
    selectPT(index) {
      this.controlPT = index;
      console.log(this.controlPT);
      this.pTShow = true;
      this.getparticipantData(0);
    },
    pTHandlePage(value) {
      this.pTPageNum = value;
      this.getparticipantData(this.pTPageNum - 1);
    },
    /////////////计算总分润规则区间////////////
    computeFirs(a, b, c) {
      let arrFirst = [];
      for (let i = 1; i < 8; i++) {
        let result = c * b + a * b * i;
        let temp = {};
        temp.index = i;
        temp.result = result;
        arrFirst.push(temp);
      }
      let percent = 90;
      let preview = [];
      for (let i = 0; i < arrFirst.length; i++) {
        let temp = {};
        if (i === 0) {
          temp.intervalBegin = 0;
          temp.allotType = 1;
          temp.intervalEnd = arrFirst[0].result;
          temp.percent = 100;
        } else {
          temp.intervalBegin = arrFirst[i - 1].result;
          temp.intervalEnd = arrFirst[i].result;
          temp.percent = percent;
        }
        percent = percent - 10;
        preview.push(temp);
        if (i === arrFirst.length - 1) {
          preview.push({ intervalBegin: arrFirst[i].result, intervalEnd: null, percent: percent });
        }
      }
      return preview;
    },
    /////////计算客户方规则区间//////
    computeKehu(a, b, c) {
      this.resultKeHu = c * b + a * b;
      let resultGong = a * b;
      let resultZhu = b * c;
      let percentGong = (resultGong / (resultGong + resultZhu)).toFixed(2);
      let percentZhu = (1 - parseFloat(percentGong)).toFixed(2);
    },
    zancun() {
      let resultGong = a * b;
      let resultZhu = b * c;
      let percentGong = (resultGong / (resultGong + resultZhu)).toFixed(2);
      let percentZhu = (1 - parseFloat(percentGong)).toFixed(2);
    },
    getparticipantData(pageNum) {
      let token = this.$localStorage.storageGet("TOKEN");
      if (!token) {
        this.$router.push({
          name: "Login"
        });
        return;
      }
      let url =
        apis.relatedUser + "/" + this.getParams.row.id + "?" + "page=" + pageNum + "&size=10" + "&keyWord="

      this.$axios({
        method: "get",
        url: url,
        headers: {
          Authorization: "Bearer " + token
        }
      })
        .then(res => {
          if (res.status == "200") {
            this.participantShowData = res.data;
            this.pTShowData = res.data;
            this.participantTotal = parseInt(res.headers["x-total-count"]);
            this.pTTotal = parseInt(res.headers["x-total-count"]);
          } else {
            this.$Message.error(res.data.detail);
          }
        })
        .catch(err => {
          this.$Message.error(err.response.data.message);
        });
    },
    /////////////////项目用户列表///////////
    projectUser() {
      let token = this.$localStorage.storageGet("TOKEN");
      if (!token) {
        this.$router.push({
          name: "Login"
        });
        return;
      }
      let url =
        apis.relatedUser + "/" + this.getParams.row.id + "?" + "page=" + 0 + "&size=99999"

      this.$axios({
        method: "get",
        url: url,
        headers: {
          Authorization: "Bearer " + token
        }
      })
        .then(res => {
          if (res.status == "200") {
            let arry = [];
            res.data.forEach(element => {
              let temp = {};
              if (element.roles.length === 0 || element.roles === null) {
                this.$Message.error({
                  content: element.userName + "没有绑定角色",
                  duration: 30
                })
              } else {
                element.roles.forEach(ele => {
                  let temp = {};
                  temp.projectRoleId = ele;
                  temp.userName = element.userName;
                  temp.userId = element.userId;
                  temp.mobile = element.mobile;
                  arry.push(temp)
                })

              }
            })

            this.comFun(arry);
            this.selectData = arry;
            // res.data.forEach(element => {
            //   let arry = element.roles;
            //   let newArry = this.comFun(arry);
            //   element.projectRoles = newArry;
            // })
            // this.PTFarry = this.getPTFData(res.data);
            // console.log(this.PTFarry)
          } else {
            this.$Message.error(res.data.detail);
          }
        })
        .catch(err => {
          console.log(err)
          this.$Message.error(err.response.data.message);
        });
    },
    comFun(chuLiArry) {
      chuLiArry.forEach(ele => {
        if (ele.projectRoleId === "01") {
          ele.projectRole = "矿工"
        } else if (ele.projectRoleId === "02") {
          ele.projectRole = "矿场主"
        }
        else if (ele.projectRoleId === "03") {
          ele.projectRole = "经销商"
        }
        else if (ele.projectRoleId === "04") {
          ele.projectRole = "介绍经销商"
        }
        else if (ele.projectRoleId === "05") {
          ele.projectRole = "讲师"
        }
        else if (ele.projectRoleId === "06") {
          ele.projectRole = "平台"
        }
        else if (ele.projectRoleId === "07") {
          ele.projectRole = "股东"
        }
        else if (ele.projectRoleId === "08") {
          ele.projectRole = "员工"
        }
        else if (ele.projectRoleId === "09") {
          ele.projectRole = "投资人"
        }
      })
    },
    getPTFData(PTFarry) {
      for (let i = 0; i < PTFarry.length; i++) {
        if (PTFarry[i].projectRoles === null) {
          PTFarry.split(i, 1);
        }
        if (PTFarry[i].projectRoles.length === 1) {
          if (PTFarry[i].projectRoles[0].value = "01") {
            PTFarry.splice(i, 1);
          }
        }
      }
      for (let i = 0; i < PTFarry.length; i++) {
        PTFarry[i].projectRole = PTFarry[i].projectRoles[0].value
      }
      return PTFarry
    },
    selectFun(value) {
      this.containerData = value;
    },
    addToItem(type) {
      let newArr = []
      let clientArry = this.containerData;
      clientArry.forEach(element => {
        let temp = {};
        let index = element.indexOf("/");
        let index_1 = element.indexOf("?")
        let indexLast = element.lastIndexOf("/")
        temp.allotUserId = element.slice(0, index);
        temp.userName = element.slice(index + 1, indexLast);
        temp.projectRoleId = element.slice(indexLast + 1, index_1);
        temp.projectRole = element.slice(index_1 + 1);
        newArr.push(temp)
      })
      if (type === "客户方") {
        this.clientArry = newArr;
      }
      if (type === "平台方") {
        this.platformArry = newArr;
      }
      this.containerData = [];
      this.fruit = [];
    },
    remove(index) {
      this.clientArry.splice(index, 1);
    },
    removePT(index) {
      this.platformArry.splice(index, 1);
    },
    ///////去重///////
    unique(dataAarry) {
      let result = [];
      for (let j = 0; j < dataAarry.userAarry.length; j++) {
        if (!result) {
          result.push(dataAarry.userAarry[j]);
        } else {
          let con = true;
          for (let k = 0; k < result.length; k++) {
            if (dataAarry.userAarry[j].userId === result[k].userId) {
              con = false;
              break;
            }
          }
          if (con) {
            result.push(dataAarry.userAarry[j]);
          }
        }
      }
      dataAarry.userAarry = result;
      return dataAarry;
    },
    ok() {
      this.checkData.forEach(element => {

      })
    }
  }
};
</script>

<style scoped>
.wrapp {
  padding: 0 20px;
}

.head {
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  padding: 10px 5px;
  display: flex;
  justify-content: space-between;
}

.title {
  color: #666;
  font-size: 24px;
}

.banner {
  margin-top: 20px;
}
.item {
  margin-top: 20px;
  display: flex;
  align-items: center;
}
.item span {
  width: 100px;
}
.bannerItem {
  height: 300px;
  width: 300px;
  border: 2px solid #dcdee2;
  border-radius: 10px;
  margin-right: 20px;
  margin-bottom: 20px;
}
.boxContentSon_1 {
  height: 250px;
  overflow: hidden;
}
.srcroll {
  height: 250px;
  overflow-y: scroll;
  overflow-x: hidden;
}
/* //////////////////////////////////////////////////// */
.wrapp {
  padding: 0 20px;
}

.head {
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  padding: 10px 5px;
  display: flex;
  justify-content: space-between;
}

.title {
  color: #666;
  font-size: 24px;
}
.select {
  margin: 50px auto;
  width: 600px;
  height: 350px;
  display: flex;
  margin-bottom: 0px;
}
.box {
  width: 500px;
  height: 280px;
  border: 2px solid #dcdee2;
  border-radius: 10px;
  margin-right: 20px;
}
.boxHead {
  padding: 0 10px;
  height: 36px;
  background: #f9fafc;
  border-bottom: 1px solid #dcdee2;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.boxSearch {
  padding: 0 5px;
  margin-top: 5px;
  position: relative;
}
.boxContent {
  margin-top: 5px;
  /* padding: 0 10px; */
}
.boxContentSon {
  height: 267px;
  overflow: hidden;
}
.checkboxGroup {
  height: 267px;
  scroll-behavior: smooth;
  overflow-y: scroll;
  overflow-x: hidden;
}
.contentItem {
  height: 44px;
  line-height: 44px;
  cursor: pointer;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.contentItemNew {
  height: 44px;
  line-height: 44px;
  cursor: pointer;
  padding: 0 10px;
  display: flex;
  align-items: center;
}
.contentItem:hover {
  background: #f7f7f7;
}
.contentItemNew:hover {
  background: #f7f7f7;
}
.type {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 250px;
  margin-top: 30px;
}
.type button {
  width: 180px;
  height: 40px;
  margin-bottom: 10px;
  margin-right: 10px;
}
.sure {
  width: 200px;
  height: 100px;
  margin: 0 auto;
  margin-top: 30px;
}
.sureItem {
  display: inline-block;
  margin-left: 10px;
}
.searchIcon {
  position: absolute;
  right: 0;
  top: 2px;
  height: 20px;
  width: 30px;
}
</style>